/* 
    绘制矩形范围,截图保存到本地
 */
import VectorSource from "ol/source/Vector";
import Draw, { createBox } from "ol/interaction/Draw";
import { Fill, Stroke, Style } from "ol/style";

// 绘制矩形后,截图保存到本地
export function drawMap(map: any, imgName: string) {
  const source = new VectorSource({
    wrapX: false,
  });
  let draw = new Draw({
    source: source,
    type: "Circle",
    style: new Style({
      stroke: new Stroke({
        color: "rgba(195, 59, 83, 1)",
        width: 1,
      }),
      fill: new Fill({
        color: "rgba(195, 59, 83, 0.2)",
      }),
    }),
    geometryFunction: createBox(),
  });
  map.addInteraction(draw);
  draw.on("drawend", (evt: any) => {
    // source.clear();
    map.removeInteraction(draw);
    console.log(evt);
    map.renderSync();

    let extent = evt.feature.getGeometry().getExtent();
    //地理坐标转换屏幕坐标
    let coord = [extent[0], extent[3]];
    let leftTopPosition = map.getPixelFromCoordinate(coord);
    let coord1 = [extent[2], extent[1]];
    let bottomRightPosition = map.getPixelFromCoordinate(coord1);
    //计算框选矩形的宽度以及高度像素
    let width = Math.abs(bottomRightPosition[0] - leftTopPosition[0]);
    let height = Math.abs(bottomRightPosition[1] - leftTopPosition[1]);
    //计算框选矩形的左上角屏幕坐标
    let minx = leftTopPosition[0];
    let miny = leftTopPosition[1];
    //创建canvas元素
    let mapCanvas: any = document.getElementsByClassName("ol-layer")[0].children[0];
    let image = mapCanvas.getContext("2d");
    image.crossOrigin = "";
    let imageData = image.getImageData(minx, miny, width, height);
    console.log("imageData", imageData);
    let canvas: any = document.createElement("canvas");
    canvas.crossOrigin = "";
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").putImageData(imageData, 0, 0);
    let dataUrl = canvas.toDataURL(); //转换图片为dataURL
    let link = document.createElement("a");
    link.download = imgName;
    link.href = dataUrl;
    link.click();
    console.log("截图成功");
  });
}
